﻿/**
 * @Description: 机构管理
 * @Author: Tom
 * @Date: 2020-01-09 10:39:55
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-04-13 11:49:58
 */

$(function () {
    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        // console.log('resize...');
        var minHeight = $(window).height() - $('#dataTreeDiv').offset().top - 20;
        $('#dataTreeDiv').css('max-height', minHeight);
        $('#dataTreeDiv').css('height', minHeight);
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };
    // 根节点id(自定义)
    var rootNodeId = '101010';
    var treeObj;
    var menuType = false 
    var portaluserno = getCookie ('portaluserno')
    var configInfo=InitialParameter("/Config.json")
    var modelApi = getBaseplatformPort () 
    $(function () {
        // 获取机构上下级树
        var orgData = [];
        $.ajax({
            type: "post",
            async: false,
            // url: "/BaseAshx/Org/OrgAshx.ashx",
            // data: {
            //     stype: 'OrgManage_QueryOrgTree',
            //     orgid: rootNodeId,
            //     treetype: 'down'
            // },
            url: modelApi + 'dept/getAllDepts',
            data: {
                orgid: rootNodeId,
                treetype: 'down'
            },
            datatype: "json",
            success: function (result) {
                // console.log(result);
                var result = JSON.parse(result);
                if (result.code == 200) {
                    var data = result.data;
                    orgData = data.map(function (item, index) {
                        var mapResult = {
                            "id": item.ORG_ID,
                            "name": item.ORGSHORTNAME,
                            "pId": item.ORG_PID,
                            "status": item.ORG_LEVEL,
                            "fullName": item.ORGNAME,
                            "newId":item.ID
                        };
                        if (index == 0) {
                            mapResult.open = true;
                        }
                        return mapResult;
                    }); 
                }
            },
            error: function (err) {
                console.log(err);
                var msg = '';
                if (err.status == 405) {
                    msg = '未登录, 请先登录';
                    setTimeout(function () {
                        top.location.href = '/login/LoginNew.aspx';
                    }, 500);
                } else {
                    msg = '数据获取失败';
                }
                layer.msg(msg, {
                    shade: 0.3,
                    time: 1000 // 1秒关闭
                });
            }
        });

        // 假数据
        // {
        //     "id": "20170525091439001010",
        //     "name": "企业注册",
        //     "pId": null,
        //     "status": "1",
        //     "fullName": "02"
        // }
        queryHandler(orgData);
    });

    var setting = {
        view: {
            addDiyDom: addDiyDom,
            expandSpeed: 0,
        },
        data: {
            simpleData: {
                enable: true //确定 zTree 初始化时的节点数据、异步加载时的节点数据、或 addNodes 方法中输入的 newNodes 数据是否采用简单数据模式 (Array) 
            }
        },
        callback: {
            // 点击
            onClick: zTreeOnClick,
            // 展开
            onExpand: zTreeOnExpand,
            // 关闭
            onCollapse: zTreeOnCollapse
        }
    };

    /**
     * 自定义DOM节点
     */
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 15;
        var liObj = $("#" + treeNode.tId);
        var aObj = $("#" + treeNode.tId + "_a");
        var switchObj = $("#" + treeNode.tId + "_switch");
        var icoObj = $("#" + treeNode.tId + "_ico");
        var spanObj = $("#" + treeNode.tId + "_span");
        aObj.attr('title', '');
        aObj.append('<div class="divTd swich fnt" style="width:50%"></div>');
        var div = $(liObj).find('div').eq(0);

        $('span[id^="dataTree"][id$="ico"]').css("margin-top", "9px");
        //从默认的位置移除
        switchObj.remove();
        spanObj.remove();
        icoObj.remove();
        //在指定的div中添加
        div.append(switchObj);
        div.append(spanObj);
        //隐藏了层次的span
        var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
        switchObj.before(spaceStr);
        //图标垂直居中
        icoObj.css("margin-top", "9px");
        switchObj.after(icoObj);
        var editStr = '';
        // debugger;
        //宽度需要和表头保持一致
        editStr += '<div class="divTd" style="width:50%">' + (treeNode.fullName == null ? '' : treeNode.fullName) + '</div>';
        // editStr += '<div class="divTd" style="width:10%">' + (treeNode.status == '1' ? '有效' : '无效') + '</div>';
        // editStr += '<div class="divTd" style="width:20%">' + treeNode.status + '</div>';
        // console.log(treeNode);
        aObj.append(editStr);
    }
    //初始化列表
    function queryHandler(zTreeNodes) {
        //初始化树
        //第一个参数为zTree的DOM容器，第二个为zTree设置详情可见官网api,第三个为zTree的节点数据
        treeObj = $.fn.zTree.init($("#dataTree"), setting, zTreeNodes);
        //添加表头
        var li_head = '<li class="head">' +
            '<a>' +
            '<div class="divTd" style="width:50%">机构简称</div>' +
            '<div class="divTd" style="width:50%">机构全称</div>' +
            // '<div class="divTd" style="width:10%">机构代码</div>' +
            // '<div class="divTd" style="width:20%">机构类型</div>' +
            '</a>' +
            '</li >';
        var rows = $("#dataTree").find('li');
        if (rows.length > 0) {
            rows.eq(0).before(li_head);
        } else {
            $("#dataTree").append(li_head);
            $("#dataTree").append('<li ><div style="text-align: center;line-height: 30px;" >无符合条件数据</div></li>');
        }
    }

    // 当前选中节点
    var nowNode;

    function zTreeOnClick(event, treeId, treeNode) {
        if (nowNode == treeNode) {
            // 重复点击了 
            $('.returnBtn').click();
            return;
        }
        // 修改当前节点
        menuType = true 
        nowNode = treeNode;
        $('#direction').html(treeNode.name);
        $('.addBtn, .deleteBtn, .editBtn, .returnBtn, .userBtn, .powerBtn').removeClass('unable');
    }

    function zTreeOnExpand(event, treeId, treeNode) {
        //alert(treeNode.tId + ", " + treeNode.name);
    }

    function zTreeOnCollapse(event, treeId, treeNode) {
        //alert(treeNode.tId + ", " + treeNode.name);
    }

    // 点击返回根目录
    $('.returnBtn').on('click', function (e) {
        var $this = $(this);
        if (!$this.hasClass('unable')) {
            $this.addClass('unable');
            $('.addBtn, .deleteBtn, .editBtn, .returnBtn, .userBtn, .powerBtn').addClass('unable'); 
            nowNode = undefined;
            $('.curSelectedNode').removeClass('curSelectedNode');
            $('#direction').html('根目录');
        }
    });

    // 增加事件 参数：当前id，当前level，增加的简称，增加的全称
    $('.addBtn').on('click', function () {
        if (menuType) {
            var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        var html = '<input style="display:none">';
        html += '<span>' + '机构简称' + '：</span><input maxlength="20" id="nameInput" type="text" class="layui-layer-input" autocomplete="off"> <br/>' +
            '<span>' + '机构全称' + '：</span><input maxlength="20" id="fullNameInput" type="text" class="layui-layer-input" autocomplete="off"><br/ >';
        var content = '<div>' + html + '</div>';
        layer.open({
            id: 1,
            type: 1,
            title: '请填写相关信息',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['保存', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function (index, layero) {
                layer.close(index);
            },
            btn1: function (index, layero) {
                var name = layero.find('#nameInput').val();
                var fullName = layero.find('#fullNameInput').val();
                if (!name) {
                    layer.msg('请输入机构简称', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!fullName) {
                    layer.msg('请输入机构全称', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                $.ajax({
                    type: 'post',
                    async: false,
                    // url: '/BaseAshx/Org/OrgAshx.ashx',
                    // data: {
                    //     stype: 'OrgManage_InsertOrg',
                    //     orgpid: nowNode ? nowNode.id : rootNodeId,
                    //     shortname: name,
                    //     fullname: fullName
                    // },
                    url: modelApi + 'dept/insertDept',
                    data: {
                        orgPid: nowNode ? nowNode.id : rootNodeId,
                        orgshortname: name,
                        orgname: fullName
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            // 添加节点
                            var newNode = treeObj.addNodes(nowNode, {
                                id: result.data,
                                "name": name, // 机构简称
                                "fullName": fullName, // 机构全称
                                'status': parseInt(nowNode.status) + 1
                            }, true);

                            layer.close(index);
                            if (nowNode) {
                                var $switchBtn = $("#" + nowNode.tId + "_switch");
                                var className = $switchBtn.attr('class');
                                if (className.indexOf('_close') >= '0') {
                                    $switchBtn.click();
                                }
                            }
                        } else {
                            layer.msg(result.msg, {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            },
        });
        } else {
            layer.msg('请选择需要增加的机构', {icon: 0});
        }
    });

    // 编辑事件 参数：当前id，编辑的东西
    $('.editBtn').on('click', function () {
        if (menuType) {
            var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }

        var html = '<input style="display:none">';
        html += '<span>' + '机构简称' + '：</span><input maxlength="20" id="nameInput" type="text" class="layui-layer-input" autocomplete="off" value="' + nowNode.name + '"> <br/>' +
            '<span>' + '机构全称' + '：</span><input maxlength="20" id="fullNameInput" type="text" class="layui-layer-input" autocomplete="off" value="' + nowNode.fullName + '"><br/ >';
        var content = '<div>' + html + '</div>';
        layer.open({
            id: 2,
            type: 1,
            title: '请编辑机构信息',
            skin: 'layui-layer-prompt',
            // content: '<div id="" style="color: #000">' +
            //     '机构简称：<input id="nameInput" type="text" class="layui-layer-input" value="" style="margin-bottom:10px; margin-top:5px" autocomplete="off">' +
            //     '机构全称：<input id="fullNameInput" type="text" class="layui-layer-input" value="" style="margin-top:5px" autocomplete="off">' +
            //     '</div>',
            content: content,
            btn: ['保存', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function (index, layero) {
                layer.close(index);
            },
            btn1: function (index, layero) {  
                var oldName = nowNode.name;
                var oldFullName = nowNode.fullName;
                var name = layero.find('#nameInput').val();
                var fullName = layero.find('#fullNameInput').val();
                if (!name) {
                    layer.msg('机构简称不可改为空', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (!fullName) {
                    layer.msg('机构全称不可改为空', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                if (name == nowNode.name && fullName == nowNode.fullName) {
                    layer.msg('无修改, 请修改后再保存', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                } 
                let orgshortname = name == nowNode.name ? '' : name
                $.ajax({
                    type: 'post',
                    async: false,
                    // url: '/BaseAshx/Org/OrgAshx.ashx',
                    // data: {
                    //     stype: 'OrgMange_UpdateOrg',
                    //     id: nowNode ? nowNode.id : rootNodeId,
                    //     shortname: name == nowNode.name ? '' : name,
                    //     fullname: fullName == nowNode.fullName ? '' : name,
                    // },
                    url: modelApi + 'dept/updateDept',
                    data: {
                        // orgPid: nowNode ? nowNode.id : rootNodeId,
                        orgshortname,
                        orgname:fullName, 
                        id:nowNode.newId
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            // 更新节点
                            nowNode.name = name;
                            nowNode.fullName = fullName;
                            var newNode = treeObj.updateNode(nowNode);
                            $('span[id^="dataTree"][id$="ico"]').css("margin-top", "9px");
                            $('.curSelectedNode .divTd').eq(1).html(fullName);
                            layer.close(index);
                            layer.msg('修改成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            // if (nowNode) {
                            //     var $switchBtn = $("#" + nowNode.tId + "_switch");
                            //     var className = $switchBtn.attr('class');
                            //     if (className.indexOf('_close') >= '0') {
                            //         $switchBtn.click();
                            //     }
                            // }
                        } else {
                            layer.msg('修改失败', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            },
        });
        } else {
            layer.msg('请选择要编辑的机构', {icon: 0});
        }
    });

    // 删除事件 参数：当前id
    $('.deleteBtn').on('click', function () {
        if (menuType) {
            var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        layer.open({
            // id: 3,
            type: 1,
            title: '注意! 您正在进行危险操作!',
            skin: 'layui-layer-prompt',
            content: '<div>' +
                '确定要删除当前所选机构吗?' +
                '</div>',
            btn: ['确定', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function (index, layero) {
                layer.close(index);
            },
            btn1: function (index, layero) {
                layer.close(index);
                layer.open({
                    // id: 3,
                    type: 1,
                    title: '请再次注意!',
                    skin: 'layui-layer-prompt',
                    content: '<div>' +
                        '该操作不可撤销, 确定要删除当前所选机构吗?' +
                        '</div>',
                    btn: ['确定', '取消'],
                    shadeClose: true, //点击遮罩关闭
                    btn2: function (index, layero) {
                        layer.close(index);
                    },
                    btn1: function (index, layero) {
                        $.ajax({
                            type: 'post',
                            async: false,
                            // url: '/BaseAshx/Org/OrgAshx.ashx',
                            // data: {
                            //     stype: 'OrgMange_DeleteOrg',
                            //     id: nowNode ? nowNode.id : rootNodeId
                            // },
                            url: modelApi + 'dept/deleteDept',
                            data: {
                                orgId: nowNode ? nowNode.id : rootNodeId
                            },
                            datatype: 'json',
                            success: function (result) {
                                result = JSON.parse(result);
                                if (result.code == 200) {
                                    // 删除成功
                                    var newNode = treeObj.removeNode(nowNode);
                                    //$('span[id^="dataTree"][id$="ico"]').css("margin-top", "9px");
                                    layer.msg('删除成功', {
                                        shade: 0.3,
                                        time: 1000 // 1秒关闭
                                    });
                                    layer.close(index);
                                    setTimeout(function () {
                                        location.href = location.href;
                                    }, 500);
                                } else {
                                    layer.msg('该机构或下属机构存在人员, 请先处理人员再执行删除操作', {
                                        shade: 0.3,
                                        time: 2000 // 1秒关闭
                                    });
                                    layer.close(index);
                                }
                            },
                            error: function (error) {
                                console.log(error);
                            }
                        });
                    },
                });
                $('.layui-layer-title').css({
                    color: 'red',
                });
                // $('.layui-layer-btn0').css({
                //     'background-color':'red'
                // });
            },
        });
        $('.layui-layer-title').css({
            color: 'red',
        });
        // $('.layui-layer-btn0').css({
        //     'background-color':'red'
        // });
        } else {
            layer.msg('请选择需要删除的机构', {icon: 0});
        }
    });

    // 成员管理 参数：
    $('.userBtn').on('click', function () {
        if (menuType) {
            var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        var html = '<div id="member" class="">' +
            '<div id = "memberLeft"class = "" >' +
            '<div id="leftTitle" class="memberTitle" >待选用户</div>' +
            '<div id="leftContent" class="" ><ul></ul></div>' +
            '</div > <div id="memberCenter" class="" ><div id="btnDiv" >' +

            '<button id="toRight" class="layui-btn layui-btn-normal unable" style="margin: 0px 0px 10px 10px;">选择=></button>' +
            // '<button id="toRightAll" class="centerBtn" >全选</button>' +
            '<button id="toLeft" class="layui-btn layui-btn-danger unable" ><=删除</button>' +

            '</div> </div> <div id="memberRight" class=""><div id="rightTitle" class="memberTitle" > 已选用户 </div> <div id="rightContent" class="" > <ul> </ul > </div> </div > </div>';
        layer.open({
            type: 1,
            title: '编辑' + nowNode.name + '成员',
            // title: '编辑' + '成员',
            skin: 'layui-layer-prompt',
            content: html,
            btn: ['确定', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function (index, layero) {
                layer.close(index);
            },
            btn1: function (index, layero) {
                var data = [];
                $('#rightContent li:visible').each(function () {
                    var $this = $(this);
                    data.push($this.attr('userid'));
                });
                data = data.join()
                $.ajax({
                    type: 'post',
                    async: false,
                    // url: '/BaseAshx/Org/OrgAshx.ashx',
                    // data: {
                    //     stype: 'OrgManage_SetOrgUsers',
                    //     id: nowNode ? nowNode.id : rootNodeId,
                    //     newList: JSON.stringify(data),
                    // },
                    url: modelApi + 'dept/setDeptUser',
                    data: {
                        orgId: nowNode ? nowNode.id : rootNodeId,
                        users: data,
                    },
                    datatype: 'json',
                    success: function (result) {
                        result = JSON.parse(result);
                        if (result.code == 200 ) {
                            layer.msg('编辑成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            layer.close(index);
                        } else {
                            layer.msg('编辑成员失败', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            },
        });
        $('.layui-layer').css({
            width: 'fit-content',
        });
        $('.layui-layer').css({
            left: ($(window).width() - $('.layui-layer').width()) / 2 + 'px'
        });

        // 请求成员列表
        $.ajax({
            type: 'post',
            async: false,
            // url: '/BaseAshx/Org/OrgAshx.ashx',
            // data: {
            //     stype: 'OrgManage_GetUserListByOrgID',
            //     id: nowNode ? nowNode.id : rootNodeId
            // },
            url: modelApi + 'dept/getUserListByOrgID',
            data: {
                orgId: nowNode ? nowNode.id : rootNodeId
            },
            datatype: 'json',
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 200) {
                    var data = result.data;
                    // console.log(data);
                    var htmlLeft = '';
                    var htmlRight = '';
                    data.map(function (item, index) {
                        // console.log(item.CHECKED);
                        htmlLeft += '<li userid="' + item.ID + '"' + (item.CHECKED == '1' ? 'class="none"' : '') + '>' + item.NAME + '</li>';
                        htmlRight += '<li userid="' + item.ID + '"' + (item.CHECKED == '0' ? 'class="none"' : '') + '>' + item.NAME + '</li>';
                    });
                    $('#leftContent ul').html(htmlLeft);
                    $('#rightContent ul').html(htmlRight);

                    // 选择左边
                    // 双击
                    $('#leftContent li').on('dblclick', function () {
                        var $this = $(this);
                        $this.removeClass('active').hide();
                        var index = $this.index();
                        $('#rightContent li').eq(index).show();
                    });
                    // 单击
                    var $leftLastClick;
                    $('#leftContent li').on('click', function (e) {
                        var $this = $(this);
                        if (e.shiftKey && $leftLastClick) {
                            $('#leftContent li').removeClass('active');
                            // 选中之间的所有项目
                            var index1 = $leftLastClick.index();
                            var index2 = $this.index();
                            if (index1 < index2) {
                                for (var i = index1; i <= index2; i++) {
                                    $('#leftContent li').eq(i).addClass('active');
                                }
                            } else {
                                for (var i = index2; i <= index1; i++) {
                                    $('#leftContent li').eq(i).addClass('active');
                                }
                            }
                            // $leftLastClick = undefined;
                            return;
                        }
                        setTimeout(function () {
                            if ($this.hasClass('active')) {
                                $this.removeClass('active');
                                $leftLastClick = undefined;
                            } else {
                                $this.addClass('active');
                                $leftLastClick = $this;
                            }
                            if ($('#leftContent .active').length) {
                                $('#toRight').removeClass('unable');
                            } else {
                                $('#toRight').addClass('unable');
                            }
                        }, 100);
                    });

                    // 选择右边
                    // 双击
                    $('#rightContent li').on('dblclick', function () {
                        if (nowNode.id == '10101003') {
                            layer.msg('游客组禁止删除成员', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            return;
                        } 
                        var $this = $(this);
                        $this.removeClass('active').hide();
                        var index = $this.index();
                        $('#leftContent li').eq(index).show().removeClass('active');
                    });
                    $('#rightContent li').on('click', function () {
                        var $this = $(this);
                        if ($this.hasClass('active')) {
                            $this.removeClass('active');
                        } else {
                            $this.addClass('active');
                        }
                        if ($('#rightContent .active').length) {
                            $('#toLeft').removeClass('unable');
                        } else {
                            $('#toLeft').addClass('unable');
                        }
                    });

                    // 点击选择
                    $('#toRight').on('click', function () {
                        var $this = $(this);
                        if ($this.hasClass('unable')) {
                            return;
                        }
                        $('#leftContent .active').each(function () {
                            var $this = $(this);
                            $this.removeClass('active').hide();
                            var index = $this.index();
                            $('#rightContent li').eq(index).show();
                        });
                        $this.addClass('unable');
                    });

                    // 点击全选
                    $('#toRightAll').on('click', function () {
                        $('#leftContent li').removeClass('active').hide();
                        $('#rightContent li').show();
                    });

                    // 点击删除
                    $('#toLeft').on('click', function () {
                        var $this = $(this);
                        if ($this.hasClass('unable')) {
                            return;
                        }
                        if (nowNode.id == '10101003') {
                             layer.msg('游客组禁止删除成员', {
                                 shade: 0.3,
                                 time: 1000 // 1秒关闭
                             });
                            return;
                        }
                        $('#rightContent .active').each(function () {
                            var $this = $(this);
                            $this.removeClass('active').hide();
                            var index = $this.index();
                            $('#leftContent li').eq(index).show();
                        });
                        $this.addClass('unable');
                    });
                } else {
                    layer.msg('成员列表获取失败,请稍候再试', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
        } else {
            layer.msg('请选择需要分配成员管理的机构', {icon: 0});
        }
    });

    // 权限管理 参数：当前id
    $('.powerBtn').on('click', function () {
        if (menuType) {
            var $this = $(this);
            if ($this.hasClass('unable')) {
                return;
            }
            var html = '<div class="tree"></div><div class="powerChecked"><div id="rightTitle" class="memberTitle"> 已选权限 </div><ul></ul></div>';
            layer.open({
                type: 1,
                title: '编辑' + nowNode.name + '权限',
                // title: '编辑' + '成员',
                skin: 'layui-layer-prompt',
                content: html,
                btn: ['确定', '取消'],
                shadeClose: true, //点击遮罩关闭
                btn2: function (index, layero) {
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    var updateData = [];
                    $('.powerChecked li').each(function (index, item) {
                        updateData.push(this.id.split('tree-')[1]);
                    });
                    updateData = updateData.join() 
                    // return;
                    $.ajax({
                        type: 'post',
                        async: false,
                        // url: '/BaseAshx/Org/OrgAshx.ashx',
                        // data: {
                        //     stype: 'OrgManage_SetOrgMenus',
                        //     id: nowNode ? nowNode.id : rootNodeId,
                        //     newList: JSON.stringify(updateData)
                        // },
                        url: modelApi + 'dept/setDeptMenu',
                        data: {
                            orgId: nowNode ? nowNode.id : rootNodeId,
                            menuIds: updateData
                        },
                        datatype: 'json',
                        success: function (result) {
                            result = JSON.parse(result);
                            if (result.code == 200) {
                                layer.msg('编辑成功', {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                layer.close(index);
                            } else {
                                layer.msg('编辑失败,请稍候再试', {
                                    shade: 0.3,
                                    time: 1000 // 1秒关闭
                                });
                                layer.close(index);
                            }
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    });
                },
            });
    
            // 请求机构菜单
            $.ajax({
                type: 'post',
                async: false,
                // url: '/BaseAshx/Org/OrgAshx.ashx',
                // data: {
                //     stype: 'UserManage_GetMenuList',
                //     id: nowNode ? nowNode.id : rootNodeId
                // },
                url: modelApi + 'dept/getDeptMenu',
                data: {
                    orgId: nowNode ? nowNode.id : rootNodeId
                },
                datatype: 'json',
                success: function (result) {
                    result = JSON.parse(result);
                    if (result.code == 200) {
                        var nodes = result.data;
                        // 处理树结构数组生成多层嵌套json对象
                        var nodesMap = {};
                        // 已选机构数据
                        var checkedId = [];
                        nodes.map(function (item, index) {
                            nodesMap[item.ID] = $.extend(item, {
                                name: item.NAME,
                                checked: item.CHECKED,
                                id: item.ID,
                            });
                            if (item.CHECKED == '1') {
                                checkedId.push(item);
                            }
                        });
    
                        var resultNode = [];
                        var rootId = '';
                        nodes.map(function (item, index) {
                            if (nodesMap[item.PID]) {
                                nodesMap[item.PID].children = nodesMap[item.PID].children || [];
                                nodesMap[item.PID].children.push(item);
                            } else {
                                if (rootId && rootId !== item.PID) {
                                    console.error('数据错误(有多个根节点)');
                                    return false;
                                }
                                rootId = item.PID;
                            }
                        });
                        for (var key in nodesMap) {
                            if (nodesMap[key].PID == rootId) {
                                nodesMap[key].open = false;
                                resultNode.push(nodesMap[key]);
                            }
                        }
                        $(".tree").tree(resultNode, []);
                        var html = '';
                        checkedId.map(function (item, index) {
                            html += '<li style="overflow:hidden" id="tree-' + item.id + '">' + item.name + '</li>';
                        });
                        $('.powerChecked ul').html(html);
                        $('.layui-layer').css({
                            width: 'fit-content',
                        });
                        $('.layui-layer-content').css({
                            height: '410px',
                        });
                        $('.layui-layer').css({
                            left: ($(window).width() - $('.layui-layer').width()) / 2 + 'px',
                            top: ($(window).height() - $('.layui-layer').height()) / 2 + 'px',
                        });
                        $('.tree input').on('change', function () {
                            $(this).siblings('ul').show();
                            $(this).siblings('.isShow').css({
                                transform: 'rotate(0deg)'
                            });
                            var value = this.value;
                            var checked = this.checked;
                            if (checked) {
                                if (!$('#tree-' + value).length) {
                                    $('.powerChecked ul').append('<li style="overflow:hidden" id="tree-' + this.value + '">' + $(this).siblings('a').html() + '</li>');
                                }
                                // 其子
                                if ($(this).siblings('ul').length) {
                                    $(this).siblings('ul').find('input').each(function (index, item) {
                                        $(item).prop('checked', true);
                                        if (!$('#tree-' + item.value).length) {
                                            $('.powerChecked ul').append('<li style="overflow:hidden" id="tree-' + item.value + '">' + $(item).siblings('a').html() + '</li>');
                                        }
                                    });
                                }
                                // 其父
                                if ($(this).parent('li').parent('ul').siblings('input').length) {
                                    var $parent = $(this).parent('li').parent('ul').siblings('input');
                                    $parent.prop('checked', true);
                                    if ($('#tree-' + $parent.val()).length == 0) {
                                        $('.powerChecked ul').append('<li style="overflow:hidden" id="tree-' + $parent[0].value + '">' + $parent.siblings('a').html() + '</li>');
                                    }
                                }
                            } else {
                                $('#tree-' + value).remove();
                                // 其子
                                if ($(this).siblings('ul').length) {
                                    $(this).siblings('ul').find('input').each(function (index, item) {
                                        $(item).prop("checked", false);
                                        $('#tree-' + item.value).remove();
                                    });
                                }
                                // 其父
                                if ($(this).parent('li').parent('ul').siblings('input').length) {
                                    var $parent = $(this).parent('li').parent('ul').siblings('input');
                                    $parent.prop("checked", false);
                                    $('#tree-' + $parent[0].value).remove();
                                }
                            }
                            // 其子
    
                        });
                    } else {
                        layer.msg('权限列表请求失败,请稍候再试', {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
    
            // 假数据
            /* var data = [{
                "name": "所有权限123",
                "open": false,
                "checked": false,
                "children": [{
                        "name": "储物柜管理",
                        "open": true,
                        "checked": false,
                        "children": [{
                                "name": "储物柜列表",
                                "checked": false,
                                "open": false,
                                "children": [{
                                    "name": "修改价格",
                                    "id": 43,
                                    "checked": false
                                }]
                            },
                            {
                                "name": "计费类型",
                                "checked": false,
                                "open": true,
                                "children": [{
                                        "name": "删除",
                                        "checked": false
                                    },
                                    {
                                        "name": "提交编辑",
                                        "checked": false
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "name": "广告业务",
                        "checked": false,
                    },
                    {
                        "name": "个人中心",
                        "open": true,
                        "ico": false,
                        "checked": false,
                        "children": [{
                                "name": "资料修改",
                                "id": 5,
                                "ico": false,
                                "checked": false,
                                "open": true,
                                "children": []
                            },
                            {
                                "name": "密码修改",
                                "id": 6,
                                "ico": false,
                                "checked": false,
                                "open": true,
                                "children": []
                            },
                            {
                                "name": "资金账户",
                                "id": 41,
                                "ico": false,
                                "checked": false,
                                "open": true,
                                "children": [{
                                        "name": "资金账户绑定微信",
                                        "id": 39,
                                        "ico": false,
                                        "checked": false
                                    },
                                    {
                                        "name": "资金账户绑定支付宝",
                                        "id": 40,
                                        "ico": false,
                                        "checked": false
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "name": "日志管理",
                        "open": true,
                        "ico": false,
                        "checked": false,
                        "children": [{
                                "name": "错误日志",
                                "id": 30,
                                "ico": false,
                                "checked": false,
                                "open": true,
                                "children": [{
                                        "name": "详情",
                                        "id": 31,
                                        "ico": false,
                                        "checked": false
                                    },
                                    {
                                        "name": "删除",
                                        "id": 32,
                                        "ico": false,
                                        "checked": false
                                    }
                                ]
                            },
    
                        ]
                    }
                ]
            }]; */
        } else {
            layer.msg('请选择需要分配权限的机构', {icon: 0});
        }
    });

});